<template>
  <div class="img-input">
    <el-upload
      v-model:file-list="files"
      class="upload-demo"
      action="http://127.0.0.1:4523/m1/5357632-5029353-default/image"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      list-type="picture"
      :limit="1"
      :on-exceed="handleExceed"
      :on-success="handleSuccess"
    >
      <el-button type="primary">点击上传</el-button>
      <template #tip>
        <div class="el-upload__tip">
          仅支持 jpg/png 格式的图片，大小不超过 500kb
        </div>
      </template>
    </el-upload>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { ElUpload, ElMessageBox, ElNotification } from 'element-plus';
import { useStore } from 'vuex';

const store = useStore();
const upload = ref(null);

let files = ref([
  {
    name: store.state.CreateProject.project.imageName,
    url:'src/assets/images/'+store.state.CreateProject.project.imageName,
  }
]);
// 预览图片
const handlePreview = (uploadFile) => {
  ElMessageBox.alert(`<img src="${uploadFile.url}" alt="${uploadFile.name}" style="width: 100%; max-width: 300px;"/>`, '预览图片', {
    dangerouslyUseHTMLString: true,
    confirmButtonText: '确定',
  });
};

// 移除图片
const handleRemove = (uploadFile) => {
  files = [];
  store.commit('CreateProject/updateProjectImage', '');
};

// 上传文件超过限制时的提示
const handleExceed = (files) => {
  ElMessageBox.alert(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件`, '提示', {
    confirmButtonText: '确定',
  });
};

// 文件上传成功后的处理
const handleSuccess = (response, uploadFile, fileList) => {
  store.commit('CreateProject/updateProjectImage', uploadFile.name);
  files.value = [{ name: uploadFile.name, url:`src/assets/images/${uploadFile.name}` }];
  // console.log(files.value);
  ElNotification({
    title: '成功',
    message: '图片预上传成功',
    type: 'success',
  });
};
</script>

<style scoped>
.img-input {
  margin-bottom: 20px;
}

.upload-demo {
  display: inline-block;
}

.el-upload__tip {
  font-size: 12px;
  color: #999;
}
</style>
